<?php

namespace App\Constant;
/**
 *
 * User: linyi(linyi05@baidu.com)
 * Date: 2017/9/3
 * Time: 10:59
 */
class Error
{
    const OK = 0;
    const OK_MSG = '操作成功';

    const CANNOT_FIND_ERRNO = 999;
    const CANNOT_FIND_ERRNO_MSG = '找不到对应错误号: %s, 请确认是否配置正确';

    const INVALID_PARAM = 100;
    const INVALID_PARAM_MSG = '非法参数：%s';

    const NO_PERMISSION = 101;
    const NO_PERMISSION_MSG = '无权限';

    const NOT_EXIST = 102;
    const NOT_EXIST_MSG = '未找到';

    const DB_ERROR = 103;
    const DB_ERROR_MSG = '数据库出错';

    const FORM_VALIDATION_ERROR = 104;
    const FORM_VALIDATION_ERROR_MSG = '表单数据校验出错';


    const APPLY_OPENID_LIMIT = 200;
    const APPLY_OPENID_LIMIT_MSG = '每个微信用户每个月只能提交一次';
    const APPLY_GRADE_INVALID = 201;
    const APPLY_GRADE_INVALID_MSG = '年级和申请岗位不符';
    const APPLY_STATUS_INVALID = 202;
    const APPLY_STATUS_INVALID_MSG = '该表单禁止审核';

    public static function getError($code, $args = '', $data = '')
    {
        static $constants = null;
        if ($constants == null) {
            $constants = self::getClassConstants(__CLASS__);
            $constants = array_flip($constants);
        }
        $const = isset($constants[$code]) ? $constants[$code] : 'CANNOT_FIND_ERRNO';

        // 记录未定义错误码
        $const === 'CANNOT_FIND_ERRNO' && $args = $code;

        $errConst = __CLASS__ . '::' . $const;
        $eorConst = $errConst . '_MSG';

        $code = constant($errConst);
        $msg = constant($eorConst);
        $args !== null && $msg = sprintf($msg, $args);

        return [
            'error_code' => $code,
            'error_msg' => $msg,
            'data' => $data,
        ];
    }

    /**
     * 获取类常量
     * @param $classname
     * @return mixed
     */
    public static function getClassConstants($classname)
    {
        static $constants = [];

        if (empty($constants[$classname])) {
            $reflect = new \ReflectionClass($classname);
            $constants[$classname] = $reflect->getConstants();
        }

        return $constants[$classname];
    }
}